const { Student, Class, Dormitory } = require('../models/db');

// 统一响应格式
const ok = (res, data, extra = {}) => res.json({ success: true, data, ...extra });
const fail = (res, code = 500, message = '服务器错误') => res.status(code).json({ success: false, message, code });

// 数据映射：服务器 -> 客户端
const mapStudentToClient = (s) => ({
  _id: s._id?.toString(),
  id: s._id?.toString(),
  studentId: s.studentId,
  name: s.name,
  gender: s.gender,
  academy: s.academy,
  marketDepartment: s.marketDepartment || undefined,
  admissionDate: s.admissionDate ? new Date(s.admissionDate).toISOString().split('T')[0] : undefined,
  classId: s.class ? (s.class._id?.toString?.() || s.class?.toString?.()) : undefined,
  className: s.class?.className || undefined,
  stage: s.stage,
  dormitoryId: s.dormitory ? (s.dormitory._id?.toString?.() || s.dormitory?.toString?.()) : undefined,
  dormitoryName: s.dormitory ? `${s.dormitory.building}-${s.dormitory.floor}层-${s.dormitory.roomNumber}` : undefined,
  phone: s.phone,
  status: s.status,
  // 通过班级获取讲师和导员
  lecturerName: s.class && s.class.lecturer ? (s.class.lecturer.name || undefined) : undefined,
  advisorName: s.class && s.class.advisor ? (s.class.advisor.name || undefined) : undefined,
  teacherComments: s.teacherComments || [],
  createdAt: s.createdAt ? new Date(s.createdAt).toISOString() : undefined,
  updatedAt: s.updatedAt ? new Date(s.updatedAt).toISOString() : undefined,
});

// 数据映射：客户端 -> 服务器
const mapClientToStudent = (b) => ({
  studentId: b.studentId,
  name: b.name,
  gender: b.gender,
  academy: b.academy,
  marketDepartment: b.marketDepartment,
  admissionDate: b.admissionDate ? new Date(b.admissionDate) : undefined,
  class: b.classId,
  stage: b.stage,
  dormitory: b.dormitoryId,
  phone: b.phone,
  status: b.status,
  teacherComments: b.teacherComments || [],
  updatedAt: new Date(),
});

// 获取所有学生
exports.getAllStudents = async (req, res) => {
  try {
    const { page = 1, limit = 20, academy, status, className, stage } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(limit);
    const query = {};
    
    if (academy) query.academy = academy;
    if (status) query.status = status;
    if (stage) query.stage = stage;
    
    let students = await Student.find(query)
      .populate({
        path: 'class',
        select: 'className academy stage advisor lecturer',
        populate: [
          { path: 'lecturer', select: 'name teacherId', model: 'teacher' },
          { path: 'advisor', select: 'name teacherId', model: 'teacher' }
        ]
      })
      .populate('dormitory', 'building floor roomNumber')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));
    
    // 如果指定了班级，需要进一步过滤
    if (className) {
      const targetClass = await Class.findOne({ className });
      if (targetClass) {
        students = students.filter(s => s.class?._id?.toString() === targetClass._id.toString());
      } else {
        students = [];
      }
    }
    
    const total = await Student.countDocuments(query);
    
    // 临时调试：检查第一个学生的数据
    if (students.length > 0) {
      const firstStudent = students[0];
      if (firstStudent.class) {
        console.log('学生班级populate结果:', {
          className: firstStudent.class.className,
          lecturer: firstStudent.class.lecturer ? firstStudent.class.lecturer.name : 'null',
          advisor: firstStudent.class.advisor ? firstStudent.class.advisor.name : 'null',
          lecturerType: typeof firstStudent.class.lecturer,
          advisorType: typeof firstStudent.class.advisor
        });
      }
    }
    
    ok(res, students.map(mapStudentToClient), {
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        totalPages: Math.ceil(total / parseInt(limit))
      }
    });
  } catch (e) {
    fail(res, 500, e.message);
  }
};

// 根据ID获取学生
exports.getStudentById = async (req, res) => {
  try {
    const s = await Student.findById(req.params.id)
      .populate({
        path: 'class',
        select: 'className academy stage advisor lecturer',
        populate: [
          { path: 'lecturer', select: 'name teacherId', model: 'teacher' },
          { path: 'advisor', select: 'name teacherId', model: 'teacher' }
        ]
      })
      .populate('dormitory', 'building floor roomNumber comment');
    if (!s) return fail(res, 404, '未找到该学生');
    ok(res, mapStudentToClient(s));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

// 创建学生
exports.createStudent = async (req, res) => {
  try {
    const payload = mapClientToStudent(req.body || {});
    if (!payload.studentId || !payload.name || !payload.gender || !payload.academy || !payload.phone) {
      return fail(res, 400, '缺少必要字段: studentId | name | gender | academy | phone');
    }
    
    // 检查学号是否已存在
    const exist = await Student.findOne({ studentId: payload.studentId });
    if (exist) return fail(res, 400, '学号已存在');
    
    const created = await Student.create(payload);
    const s = await Student.findById(created._id)
      .populate('class', 'className')
      .populate('dormitory', 'building floor roomNumber');
    ok(res, mapStudentToClient(s));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

// 更新学生
exports.updateStudent = async (req, res) => {
  try {
    const payload = mapClientToStudent(req.body || {});
    payload.updatedAt = new Date();
    const updated = await Student.findByIdAndUpdate(req.params.id, payload, { new: true })
      .populate('class', 'className')
      .populate('dormitory', 'building floor roomNumber');
    if (!updated) return fail(res, 404, '未找到该学生');
    ok(res, mapStudentToClient(updated));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

// 删除学生
exports.deleteStudent = async (req, res) => {
  try {
    const deleted = await Student.findByIdAndDelete(req.params.id);
    if (!deleted) return fail(res, 404, '未找到该学生');
    ok(res, { id: req.params.id });
  } catch (e) {
    fail(res, 500, e.message);
  }
};

// 添加教师评语
exports.addTeacherComment = async (req, res) => {
  try {
    const { teacherId, teacherName, comment } = req.body;
    if (!teacherId || !teacherName || !comment) {
      return fail(res, 400, '缺少必要字段: teacherId | teacherName | comment');
    }
    
    const student = await Student.findById(req.params.id);
    if (!student) return fail(res, 404, '未找到该学生');
    
    student.teacherComments.push({
      teacherId,
      teacherName,
      comment,
      commentDate: new Date()
    });
    student.updatedAt = new Date();
    await student.save();
    
    ok(res, mapStudentToClient(student));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

